package com.zhengqiangblog.core;

import java.lang.reflect.Constructor;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.log4j.Logger;

public class ApplicationContext {

	private static final Logger logger = Logger.getLogger(ApplicationContext.class);

	private final static ConcurrentHashMap<Class<? extends Object>, Object> context = new ConcurrentHashMap<Class<? extends Object>, Object>();

	@SuppressWarnings("unchecked")
	public static <T> T get(Class<? extends T> clazz) {
		Object object = context.get(clazz);
		if (object != null) {
			return (T) object;
		}
		Constructor<? extends T> constructor = null;
		try {
			constructor = clazz.getConstructor();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		Object instance = null;
		try {
			if (constructor != null) {
				instance = constructor.newInstance();
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		if (instance != null) {
			Class<?>[] interfaces = clazz.getInterfaces();
			for (int i = 0; i < interfaces.length; i++) {
				Class<?> interfaceClass = interfaces[i];
				if (interfaceClass == InitializingBean.class) {
					InitializingBean bean = InitializingBean.class.cast(instance);
					bean.init();
					break;
				}
			}
		}
		context.putIfAbsent(clazz, instance);
		return (T) instance;
	}

}
